angular.module('memberUpdate', ['ui.grid', 'ui.grid.selection', 'ui.select', 'ui.grid.pagination',
    'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'toastr', 'common'])
    .controller('memberUpdateController',
    ['$scope', '$http', '$compile', 'toastr', 'commonService',
        function ($scope, $http, $compile, toastr) {
            var members = {};
            var complete_pm = [];
            var count = 0;

            var user = function () {
                this.u_name = '新用户';
                this.username = '';
                this.pwd = '';
                this.role = 'member';
                this.email = '';
                this.uniqueId = ++count;
                this.isIntern = false;
            };

            var tempUser = new user();
            $scope.addList = {1: tempUser};

            function validateUnique(value, schema, attr, cb) {
                $http.post('/validate/unique', {value: value, schema: schema, attr: attr}).success(function (data) {
                    if (data === 'success') {
                        cb(true);
                    } else if (data === 'fail') {
                        cb(false);
                    } else {
                        toastr.error("服务器出错");
                    }
                });
            }

            $("#u_name").on('blur', function () {
                validateUnique("'" + $("#u_name").val() + "'", "user", "u_name", function (result) {
                    !result && toastr.warning("该用户名已被注册") && $("#u_name").val("");
                });
            });
            $("#username").on('blur', function () {
                validateUnique("'" + $("#username").val() + "'", "user", "username", function (result) {
                    !result && toastr.warning("该登录账号已被注册") && $("#username").val("");
                });
            });
            $("#email").on('change', function () {
                if (!($("#email").val().match(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/))) {
                    toastr.warning("邮箱格式错误");
                    $("#email").val("");
                    $scope.$apply();
                }
            });

            if (!!$.cookie("toast")) {
                toastr.success($.cookie("toast"));
                $.cookie("toast", "");
            }

            if ($("#operation").val() === 'batchAdd') {
                $scope.query = $scope.addList[1];
            } else {
                $scope.query = {
                    username: $("#username").attr('value'),
                    u_name: $("#u_name").attr('value'),
                    role: $("#role").attr('value'),
                    manager: $("#manager").attr('value'),
                    email: $("#email").attr('value'),
                    pwd: '',
                    id: $("#uid").html(),
                    isIntern : ($("#role").attr('value') == 'intern' ? true : false)
                };
            }

            $scope.back = function () {
                window.history.back();
            };

            $scope.editList = function (id) {
                $(".active").removeClass('active');
                $("#p-list-" + id).addClass('active');
                $scope.query = $scope.addList[id];
            };

            $scope.add = function () {
                $scope.query.manager = $("#manager").val();
                if ($scope.query.isIntern) {
                    $scope.query.role = 'intern';
                } else {
                    $scope.query.role = 'member';
                }

                if (!$scope.query.u_name || !$scope.query.username || !$scope.query.email) {
                    console.log($scope.query);
                    toastr.warning('输入信息不完整或有误');
                    return;
                }

                $scope.addList[$scope.query.uniqueId] = $.extend({}, $scope.query);
                $scope.query = new user();
                $scope.addList[$scope.query.uniqueId] = $scope.query;

                $(".active").removeClass('active');

                var template = angular.element('<li id="p-list-' + $scope.query.uniqueId + '" class="list-group-item active" ng-click="editList(' +
                $scope.query.uniqueId + ')"><i class="fa fa-trash-o remove-icon" ng-click="minus(' +
                $scope.query.uniqueId + ')"></i>&nbsp;<span ng-bind="addList[' + $scope.query.uniqueId +
                '].u_name"></span></li>');
                var compiled = $compile(template)($scope);
                angular.element("#uList").append(compiled);
                $scope.addList[$scope.query.uniqueId].element = compiled;
            };

            $scope.minus = function (id) {
                window.tempId = id;
                $(".remove-mem").modal();
                $("#ensure-remove").on("click", function (event) {
                    $scope.addList[window.tempId].element.remove();
                    findPrevious();
                    $scope.addList[window.tempId] = null;
                    $(".remove-mem").modal('hide');
                });
            };

            $scope.remove = function () {
                if ($scope.query.element) {
                    $scope.query.element.remove();
                    var tempId = $scope.query.uniqueId;
                    findPrevious();
                    $scope.addList[tempId] = null;
                } else {
                    toastr.warning("不能移除第一项");
                }
            };

            function findPrevious() {
                var tempId = $scope.query.uniqueId;
                if ($scope.addList[tempId - 1]) {
                    $scope.query = $scope.addList[tempId - 1];
                    if ($(".active").length == 0) {
                        $("#p-list-" + (tempId - 1)).addClass('active');
                    }
                } else {
                    $scope.query.uniqueId--;
                    findPrevious();
                }
            }

            $scope.saveAll = function () {
                var postArray = [];
                for (var i in $scope.addList) {
                    if (!!$scope.addList[i]) {
                        if (!$scope.addList[i].username || !$scope.addList[i].u_name || !$scope.addList[i].role || !$scope.addList[i].email) {
                            console.log($scope.addList[i]);
                            toastr.warning('输入不完整,请确认输入');
                            return;
                        }
                        postArray.push($scope.addList[i]);
                    }
                }
                var items = 0;
                for (var j in $scope.addList) {
                    items++;
                }
                if (items == 1) {
                    $scope.save();
                    return;
                } else {
                    $http.post('/member/add', postArray).success(function (data) {
                        if (data === 'success') {
                            if (window.parent) {
                                window.parent.location.href = window.parent.location.href;
                            } else {
                                window.location.href = window.location.href;
                            }
                            $.cookie("toast", "保存成功");
                        } else {
                            toastr.error(data.description);
                        }
                    }).error(function () {
                        toastr.error('请检查网络连接');
                    });
                }
            };

            $scope.changeRole = function(){
                $scope.query.role = $scope.query.isIntern ? 'intern' : 'member';
            };

            $scope.save = function () {
                $scope.query.manager = $("#manager").val();
                $scope.query.id = parseInt($scope.query.id);
                var url;
                $scope.query.id ? (url = 'save') : (url = 'add');
                if (!$scope.query.username || !$scope.query.u_name || !$scope.query.role || !$scope.query.email) {
                    toastr.warning('输入不完整,请确认输入');
                    console.log($scope.query);
                    return;
                }

                $http.post('/member/' + url, $scope.query).success(function (data) {
                    if (data === 'success') {
                        if (window.parent) {
                            window.parent.location.href = window.parent.location.href;
                            $.cookie("toast", "保存成功");
                            return;
                        }
                        if ($("#operation").val() === 'batchAdd') {
                            window.location.href = window.location.href;
                            $.cookie("toast", "保存成功");
                        } else {
                            toastr.success("保存成功");
                        }
                    } else {
                        toastr.error(data.description);
                    }
                }).error(function () {
                    toastr.error('请检查网络连接');
                });
            };

            $scope.closeModal = function () {
                $(".modal-add", window.parent.document).css('display', 'none');
                $("#modal-c", window.parent.document).css('z-index', '-1');
                $("#modal-i", window.parent.document).css('z-index', '-1');
            };

            $http.get('/user/mapping').success(function (data) {
                $scope.roleMap = data.roleKey;
                for (var i in data.role) {
                    if (data.role[i] !== 'admin') {
                        if (data.role[i] === 'manager') {
                            members[data.name[i]] = i;
                            complete_pm.push(data.name[i]);
                        }
                    }
                }
                $("#manager").autocomplete({
                    source: complete_pm,
                    select: function (event, ui) {
                        $scope.query.manager = ui.item.value;
                    }
                });
            });
        }
    ]);